package com.luoxiang.socialandroid.utils

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA
import com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER
import com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT
import com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.activity.*
import com.luoxiang.socialandroid.bean.LoginBean
import com.luoxiang.socialandroid.bean.NumberBean
import com.luoxiang.socialandroid.common.Constants.MmkvConst.ACCID
import com.luoxiang.socialandroid.common.Constants.MmkvConst.IMTOKEN
import com.luoxiang.socialandroid.common.Constants.MmkvConst.KEY
import com.luoxiang.socialandroid.common.Constants.MmkvConst.TOKEN
import com.luoxiang.socialandroid.common.Constants.MmkvConst.USERID
import com.luoxiang.socialandroid.common.Constants.MmkvConst.WXPAY
import com.luoxiang.socialandroid.utils.MmkvUtil.encode
import com.netease.nis.quicklogin.QuickLogin
import com.netease.nis.quicklogin.listener.QuickLoginPreMobileListener
import com.netease.nis.quicklogin.listener.QuickLoginTokenListener
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class LoginUtil {
    companion object {
        private var initLoginJob: Job? = null
        fun initLogin(
            lifecycleOwner: LifecycleOwner,
            onResult: (Boolean) -> Unit,
            startLoading: () -> Unit = {},
            endLoading: () -> Unit = {}
        ) {
            if (initLoginJob?.isActive == true) {
                return
            }
            startLoading.invoke()
            initLoginJob = lifecycleOwner.lifecycleScope.launch {
                val quickLogin = QuickLogin.getInstance()
                quickLogin.prefetchMobileNumber(object : QuickLoginPreMobileListener() {
                    override fun onGetMobileNumberSuccess(YDToken: String, mobileNumber: String) {
                        endLoading.invoke()
                        onResult.invoke(true)
                    }

                    override fun onGetMobileNumberError(YDToken: String, msg: String) {
                        endLoading.invoke()
                        onResult.invoke(false)
                    }
                })
            }
        }

        fun startLogin(activity: Activity, result: Boolean) {
            QuickLogin.getInstance().quitActivity()
            encode(TOKEN, "")
            encode(ACCID, "")
            encode(IMTOKEN, "")
            encode(HOSTAUDIT, "")
            encode(USER_NAME, "")
            encode("phone", "")
            encode(USERID, "")
            encode("datingModeId", "")
            encode("emotioRelationId", "")
            encode("targetAgeId", "")
            encode("sexpait", "")
            encode("ed_rename", "")
            encode("isshowdialogbatch", "")
            encode("usericon", "")
            if (result) {
                val quickLogin = QuickLogin.getInstance()
                initScreenRecorderBuild(activity)
                quickLogin.onePass(object : QuickLoginTokenListener() {
                    override fun onGetTokenSuccess(YDToken: String, accessCode: String) {
                        getloginbykey(activity, 1, EXTRA, accessCode, YDToken)
                    }

                    override fun onGetTokenError(YDToken: String, msg: String) {
                        Toast.makeText(
                            activity.application,
                            R.string.mi_denglushibai,
                            Toast.LENGTH_SHORT
                        ).show()
                        val intent = Intent(
                            activity,
                            LoginActivity::class.java
                        )
                        activity.startActivity(intent)
                        QuickLogin.getInstance().quitActivity()
                    }
                })
            } else {
                val intent = Intent(
                    activity,
                    LoginActivity::class.java
                )
                activity.startActivity(intent)
            }
        }

        private fun initScreenRecorderBuild(activity: Activity) {
            val rxPermissions = RxPermissions(activity)
            rxPermissions.request(
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CHANGE_WIFI_STATE
            ).subscribe { aBoolean: Boolean -> }
        }

        /**
         * @param type
         * @param extra
         * @param accessToken 一键登录请求接口
         */
        private fun getloginbykey(
            activity: Activity,
            type: Int,
            extra: String,
            accessToken: String,
            yiToken: String
        ) {
            NetUtils.getInstance().getRequest()
            NetUtils.getInstance().apiService.getloginbykey(type, extra, accessToken, yiToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<NumberBean?> {
                    override fun onSubscribe(d: Disposable) {}
                    override fun onNext(numberBean: NumberBean?) {
                        if (numberBean != null) {
                            val data = numberBean.data
                            var decryptStr: String? = null
                            try {
                                decryptStr = AESUtil.aesDecryptString(data, KEY)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            LogUtils.i("decryptStrs", decryptStr)
                            val gson = Gson()
                            val loginkeyBean = gson.fromJson(decryptStr, LoginBean::class.java)
                            if (loginkeyBean != null) {
                                if (loginkeyBean.data != null) {
                                    if (loginkeyBean.data.user != null) {
                                        encode("phone", loginkeyBean.data.thirdId)
                                        encode(
                                            TOKEN,
                                            loginkeyBean.data.user.token
                                        )
                                        encode(GENDER, loginkeyBean.data.user.gender)
                                        encode(HOSTAUDIT, loginkeyBean.data.user.host)
                                    }
                                }
                            }
                            if (loginkeyBean != null) {
                                if (loginkeyBean.data != null) {
                                    if (loginkeyBean.data.user != null) {
                                        encode("phone", loginkeyBean.data.thirdId)
                                        encode(IMTOKEN, loginkeyBean.data.user.imToken)
                                        encode(ACCID, loginkeyBean.data.user.id)
                                        encode(USERID, loginkeyBean.data.user.id)
                                        encode(USER_NAME, loginkeyBean.data.user.name)
                                        encode(WXPAY, loginkeyBean.data.user.wxPay)
                                    }
                                }
                                if (loginkeyBean.code == 0) {
                                    if (loginkeyBean.data.user != null) {
                                        if (loginkeyBean.data.trait) {
                                            encode("keybutezhi", "ok")
                                            encode(IMTOKEN, loginkeyBean.data.user.imToken)
                                            encode(ACCID, loginkeyBean.data.user.id)
                                            encode(USERID, loginkeyBean.data.user.id)
                                            val intent = Intent(
                                                activity,
                                                HomeActivity::class.java
                                            )
                                            activity.startActivity(intent)
                                        } else {
                                            encode("keybutezhi", "")
                                            encode(IMTOKEN, loginkeyBean.data.user.imToken)
                                            encode(ACCID, loginkeyBean.data.user.id)
                                            encode(USERID, loginkeyBean.data.user.id)
                                            val intent = Intent(
                                                activity,
                                                Tezhi1Activity::class.java
                                            )
                                            activity.startActivity(intent)
                                        }
                                    } else {
                                        encode("phone", loginkeyBean.data.thirdId)
                                        val intent = Intent(
                                            activity,
                                            RegisterActivity::class.java
                                        )
                                        activity.startActivity(intent)
                                    }
                                } else {
                                    ToastUtils.showShort(R.string.mi_denglushibai)
                                    val intent = Intent(
                                        activity,
                                        LoginActivity::class.java
                                    )
                                    activity.startActivity(intent)
                                }
                            }
                        } else {
                            ToastUtils.showShort(R.string.mi_houduanweifanweishiju)
                        }
                        if (type == 1) {
                            QuickLogin.getInstance().quitActivity()
                        }
                    }

                    override fun onError(e: Throwable) {}
                    override fun onComplete() {}
                })
        }
    }
}